import os

from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem


def treeWidget_addFile(treeWidget: QTreeWidget, dir_path: str, file_endWith_list=None):
    if file_endWith_list is None:
        file_endWith_list = []
    # 读取指定目录下的子项
    sub_items = os.listdir(dir_path)
    # 遍历子项
    for i in range(len(sub_items)):
        # 如果是目录
        if os.path.isdir(dir_path + '/' + sub_items[i]):
            # 添加顶级节点
            item = QTreeWidgetItem([sub_items[i]])
            treeWidget.addTopLevelItem(item)
            # 再迭代查看其下的子项
            treeWidgetItem_addFile(item, dir_path=dir_path + '/' + sub_items[i], file_endWith_list=file_endWith_list)
        # 如果是文件, 判断其文件后缀
        else:
            for j in range(len(file_endWith_list)):
                if sub_items[i].endswith(file_endWith_list[j]):
                    # 添加顶级节点
                    item = QTreeWidgetItem([sub_items[i]])
                    treeWidget.addTopLevelItem(item)


def treeWidgetItem_addFile(treeWidgetItem: QTreeWidgetItem, dir_path: str, file_endWith_list=None):
    if file_endWith_list is None:
        file_endWith_list = []
    # 读取指定目录下的子项
    sub_items = os.listdir(dir_path)
    # 遍历子项
    for i in range(len(sub_items)):
        # 如果是目录
        if os.path.isdir(dir_path + '/' + sub_items[i]):
            # 添加节点
            item = QTreeWidgetItem([sub_items[i]])
            treeWidgetItem.addChild(item)
            # 再迭代查看其下的子项
            treeWidgetItem_addFile(item, dir_path=dir_path + '/' + sub_items[i], file_endWith_list=file_endWith_list)
        # 如果是文件, 判断其文件后缀
        else:
            for j in range(len(file_endWith_list)):
                if sub_items[i].endswith(file_endWith_list[j]):
                    # 添加顶级节点
                    item = QTreeWidgetItem([sub_items[i]])
                    treeWidgetItem.addChild(item)


def treeWidgetItem_where(treeWidgetItem: QTreeWidgetItem):
    item_list = [treeWidgetItem]
    item = treeWidgetItem
    while True:
        item = item.parent()
        if item is None:
            break
        item_list.append(item)
    item_list.reverse()
    return item_list


def treeWidgetItem_list_toPath(treeWidgetItem_list: list[QTreeWidgetItem], sep='/'):
    path = ''
    if len(treeWidgetItem_list) > 0:
        path = treeWidgetItem_list[0].text(0)
        for i in range(1, len(treeWidgetItem_list)):
            path = path + '/' + treeWidgetItem_list[i].text(0)
    return path
